



from django.db import models
from django.db.models import F, Q, Func, Value
from django.db.models.functions import Concat
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.db import transaction

User = get_user_model()

class UpperCaseField(models.CharField):
    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        if value is not None:
            return value.upper()
        return value

class PublishedYearFunc(Func):
    function = 'EXTRACT'
    template = "%(function)s(YEAR FROM %(expressions)s)"

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    birth_date = models.DateField()
    bio = models.TextField(blank=True)
    
    class Meta:
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    def books_published_in_year(self, year):
        return self.books.filter(
            Q(publish_date__year=year) & 
            ~Q(status='draft')
        )
    
    @classmethod
    def get_authors_with_books(cls):
        return cls.objects.annotate(
            book_count=models.Count('books', filter=~Q(books__status='draft'))
        ).filter(book_count__gt=0)

class Publisher(models.Model):
    name = models.CharField(max_length=100)
    address = models.TextField()
    website = models.URLField()
    code = UpperCaseField(max_length=10, unique=True)
    
    def __str__(self):
        return self.name

class Book(models.Model):
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('published', 'Published'),
        ('archived', 'Archived'),
    ]
    
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
    publisher = models.ForeignKey(Publisher, on_delete=models.SET_NULL, null=True, blank=True)
    publish_date = models.DateField()
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
    isbn = models.CharField(max_length=13, unique=True)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    pages = models.PositiveIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-publish_date', 'title']
        indexes = [
            models.Index(fields=['publish_date', 'status']),
            models.Index(fields=['author'], name='author_idx'),
        ]
    
    def __str__(self):
        return f"{self.title} by {self.author.name}"
    
    def clean(self):
        if self.publish_date and self.publish_date > timezone.now().date():
            raise ValidationError("Publish date cannot be in the future.")
    
    @classmethod
    def get_published_books(cls):
        return cls.objects.filter(status='published')
    
    @classmethod
    def get_books_by_author(cls, author_name):
        return cls.objects.filter(
            author__name__icontains=author_name
        ).select_related('author', 'publisher')
    
    @classmethod
    def bulk_update_prices(cls, book_ids, price_increase):
        with transaction.atomic():
            savepoint = transaction.savepoint()
            try:
                books = cls.objects.filter(id__in=book_ids)
                books.update(price=F('price') + price_increase)
            except Exception as e:
                transaction.savepoint_rollback(savepoint)
                raise e

class BookLoan(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='loans')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='loans')
    loan_date = models.DateField(auto_now_add=True)
    due_date = models.DateField()
    return_date = models.DateField(null=True, blank=True)
    
    class Meta:
        ordering = ['-loan_date']
        constraints = [
            models.UniqueConstraint(
                fields=['book', 'user', 'return_date'],
                name='unique_active_loan',
                condition=Q(return_date__isnull=True),
            ),
        ]
    
    def __str__(self):
        return f"{self.book.title} loaned to {self.user.username}"
    
    def save(self, *args, **kwargs):
        if not self.due_date:
            self.due_date = self.loan_date + timezone.timedelta(days=14)
        super().save(*args, **kwargs)
    
    @classmethod
    def get_active_loans(cls):
        return cls.objects.filter(return_date__isnull=True)
    
    @classmethod
    def create_multiple_loans(cls, user, book_ids):
        with transaction.atomic():
            loans = []
            for book_id in book_ids:
                book = Book.objects.get(id=book_id)
                loan = cls(book=book, user=user)
                loan.full_clean()
                loans.append(loan)
            return cls.objects.bulk_create(loans)

class BookReview(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.PositiveSmallIntegerField()
    review = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return f"Review for {self.book.title} by {self.user.username}"